package com.yjq.blog.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.yjq.blog.service.SendMessageService;
import com.yjq.blog.vo.AliMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class SendMessageServiceImpl implements SendMessageService {

    @Override
    public CommonResponse sendMessage(String phone, Map<String, Object> param, String signName, String templateCode, AliMessage message) {
        return sendMessage(Arrays.asList(phone), param, signName, templateCode, message);
    }

    @Override
    public CommonResponse sendMessage(List<String> phone, Map<String, Object> param, String signName, String templateCode, AliMessage message) {

        DefaultProfile profile = DefaultProfile.getProfile(message.getRegionId(), message.getAccessKeyId(), message.getSecret());
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");

        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        String a = StringUtils.join(phone, ",");
        request.putQueryParameter("PhoneNumbers", StringUtils.join(phone, ","));
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));

        try {
            return client.getCommonResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
        }

        return null;
    }

}
